<?php

namespace app\controller\property\bill;

use think\App;
use app\controller\property\Base;
use app\validate\bill\BillCateValidate;
use app\common\repositories\bill\BillCateRepository;

class BillCate extends Base
{
    protected $repository;

    public function __construct(App $app, BillCateRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
    }

    public function list()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param([
                'keywords' => ''
            ]);
            $data = $this->repository->getpropertyList($param, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $data['list'], 'count' => $data['count']]);
        }
        return $this->fetch('bill/cate/list', [
            'addAuth' => property_auth('propertyBillCateAdd'),
            'editAuth' => property_auth('propertyBillCateEdit'),
            'delAuth' => property_auth('propertyBillCateDel'),
            'detailAuth' => property_auth('propertyBillCateDetail')
        ]);
    }


    /**
     * 添加房间
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     */
    public function add()
    {
        $basicCateId = $this->repository->getBillCateId($this->request->propertyId, ['is_class' => 1]);
        if ($basicCateId <= 0) {
            $param = $this->request->param([
                'cate_name' => '基本费用',
                'pid' => 0,
                'is_show' => 1,
                'is_class' => 1,
            ]);
            $this->repository->addInfo($param, $this->request->propertyId);
        }
        $energyCateId = $this->repository->getBillCateId($this->request->propertyId, ['is_class' => 2]);
        if ($energyCateId <= 0) {
            $param = $this->request->param([
                'cate_name' => '能源费用',
                'pid' => 0,
                'is_show' => 1,
                'is_class' => 2,
            ]);
            $this->repository->addInfo($param, $this->request->propertyId);
        }
        $otherCateId = $this->repository->getBillCateId($this->request->propertyId, ['is_class' => 3]);
        if ($otherCateId <= 0) {
            $param = $this->request->param([
                'cate_name' => '其它费用',
                'pid' => 0,
                'is_show' => 1,
                'is_class' => 3,
            ]);
            $this->repository->addInfo($param, $this->request->propertyId);
        }
        if ($this->request->isAjax() && $this->request->isGet() && $this->request->param('get_type') == 'classData') {
            $info = $this->repository->getDetail($this->request->param('pid'));
            if ($info['is_class'] == 1) {
                $classData = $this->repository::IS_BASIC;
            } elseif ($info['is_class'] == 2) {
                $classData = $this->repository::IS_ENERGY;
            } elseif ($info['is_class'] == 3) {
                $classData = $this->repository::IS_OTHER;
            } else {
                $classData = [];
            }
            $typeIds = $this->repository->getSearch([])
                ->where('property_id', $this->request->propertyId)
                ->column('set_finance');
            foreach ($classData as $k => $v) {
                if (in_array($k, $typeIds)) {
                    unset($classData[$k]);
                }
            }
            return json()->data(['code' => 0, 'data' => $classData]);
        } else if ($this->request->isPost()) {
            $param = $this->request->param([
                'cate_name' => '',
                'picture' => '',
                'pid' => '',
                'is_show' => '',
                'set_finance' => '',
                'is_class' => '',
                'sort' => '',
            ]);
            $param['pid'] = (int)$param['pid'];
            validate(BillCateValidate::class)->scene('add')->check($param);
            if ($this->repository->cateNameExists($param['cate_name'])) {
                return $this->error('此分类名已存在');
            }
            $info = $this->repository->getDetail($this->request->param('pid'));
            if ($param['set_finance'] > 0) {
                if ($info['is_class'] == 1) {
                    $setData = $this->repository::IS_BASIC;
                } elseif ($info['is_class'] == 2) {
                    $setData = $this->repository::IS_ENERGY;
                } elseif ($info['is_class'] == 3) {
                    $setData = $this->repository::IS_OTHER;
                }
                if ($this->repository->propertyFieldExists($this->request->propertyId, 'set_finance', $param['set_finance'])) {
                    return $this->error(($setData[$param['set_finance']] ?? '') . '已存在');
                }
            }
            $param['is_class'] = $info['is_class'];
            try {
                $res = $this->repository->addInfo($param, $this->request->propertyId, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('添加费用类别失败', $e);
                return $this->error('网络失败');
            }
        } else {
            $topCateData = $this->repository->getTopCateData($this->request->propertyId, ['is_show' => 1]);
            return $this->fetch('bill/cate/add', [
                'topCateData' => $topCateData,
            ]);
        }
    }

    /**
     * 编辑菜单
     * @return array|string|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'id' => '',
                'pid' => '',
                'cate_name' => '',
                'picture' => '',
                'sort' => '',
                'is_show' => '',
            ]);
            $param['pid'] = (int)$param['pid'];
            validate(BillCateValidate::class)->scene('edit')->check($param);
            if ($param['pid'] && $param['pid'] == $param['id']) {
                return $this->error('上级分类选择错误');
            }
            if ($param['pid'] && $this->repository->getLevelById($param['pid']) > 3) {
                return $this->error('超过最大层级');
            }
            if (!$this->repository->checkChangeToChild($param['id'], $param['pid'])) {
                return $this->error('无法修改到当前分类到子集，请先修改子类');
            }
            if (!$this->repository->checkChildLevel($param['id'], $param['pid'], 4)) {
                return $this->error('子类超过最低限制，请先修改子类');
            }
            try {
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('编辑费用类别失败', $e);
                return $this->error('网络错误');
            }
        } else {
            $topCateData = $this->repository->getTopCateData($this->request->propertyId, ['is_show' => 1]);
            return $this->fetch('bill/cate/edit', [
                'info' => $info,
                'topCateData' => $topCateData
            ]);
        }
    }

    public function detail()
    {
        $cateId = (int)$this->request->param('id');
        if ($cateId <= 0) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($cateId);
        if ($info['id'] <= 0) {
            return $this->error('分类信息不存在');
        }
        return $this->fetch('bill/cate/details', [
            'info' => $info,
        ]);
    }

    public function del()
    {
        validate(BillCateValidate::class)->scene('del')->check($this->request->param());
        $id = (int)$this->request->param('id');
        $info = $this->repository->getDetail($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        try {
            if ($this->repository->hasChild($id)) {
                return $this->error('该分类存在下级分类，请先处理下级分类');
            }
            $data = $this->repository->deleteInfo($info, $this->request->userId);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            exception_log('删除费用类别失败', $e);
            return $this->error('网络失败');
        }
    }
}